package com.winai.launcher.manager;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.media.AudioAttributes;
import android.media.AudioFocusRequest;
import android.media.AudioManager;
import android.os.Build;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;

import com.arialyy.aria.core.Aria;
import com.dueeeke.videoplayer.player.VideoView;
import com.jungle.mediaplayer.base.VideoInfo;
import com.ks.projectbasictools.utils.LogUtils;
import com.winai.launcher.bean.AiMediaBean;
import com.winai.launcher.constant.Constant;
import com.winai.launcher.constant.DirectoryConstant;
import com.winai.launcher.utils.FileUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import static com.winai.launcher.constant.Constant.MEDIA_SYSTEM_UI;

@TargetApi(Build.VERSION_CODES.O)
public class VideoManager {
    private final String TAG = "launcherVideoManager";
    private Context mContext;
    private static VideoManager mInstance;

    private List<VideoInfo> videoInfoList = new ArrayList<>();
    private int index = 0;//当前正在播放的列表

    private VideoView mVideoView;
    private AudioManager mAudioManager;

    private AudioAttributes mPlaybackAttributes;
    private AudioFocusRequest mFocusRequest;
    final Object mFocusLock = new Object();
    //    boolean mPlaybackDelayed = false;//延迟播放
//    private boolean mResumeOnFocusGain = false;//在FocusGain状态是否调用resume重播
    private boolean isVideoPlaying = false;//音频是否正在播放
    private boolean commandMediaPause = false;//是否下达暂停命令
    private long startTime = 0;

    public boolean isCommandMediaPause() {
        return commandMediaPause;
    }

    public void setCommandMediaPause(boolean commandMediaPause) {
        this.commandMediaPause = commandMediaPause;
    }

    public boolean isVideoPlaying() {
        return isVideoPlaying;
    }

    private AudioManager.OnAudioFocusChangeListener mAudioFocusChangeListener = focusChange -> {
        Log.d(TAG, "focusChange = " + focusChange);
//        if (!canIn()) {
//            return;
//        }
        switch (focusChange) {
            case AudioManager.AUDIOFOCUS_GAIN://获得焦点
            case AudioManager.AUDIOFOCUS_GAIN_TRANSIENT://暂时获得焦点
            case AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_EXCLUSIVE:
                Log.d(TAG, "AUDIOFOCUS_GAIN");
                //当其他应用申请焦点之后又释放焦点会触发此回调
                //可重新播放音乐
                synchronized (mFocusLock) {
                    if (isVideoPlaying && !commandMediaPause) {
                        resume();
                        if (!mVideoView.isMute())//恢复音量
                            mVideoView.setVolume(1.0f, 1.0f);
                    }
                }
                break;
            case AudioManager.AUDIOFOCUS_LOSS://焦点丢失
                Log.d(TAG, "AUDIOFOCUS_LOSS");
                synchronized (mFocusLock) {
//                    mResumeOnFocusGain = isPlaying();
//                    mPlaybackDelayed = false;
                    if (isPlaying()) {
                        pause();
                    }
                }
                break;
            case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT://焦点暂时丢失
            case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK://此时需降低音量
                //短暂性丢失焦点，当其他应用申请AUDIOFOCUS_GAIN_TRANSIENT或AUDIOFOCUS_GAIN_TRANSIENT_EXCLUSIVE时，
                //会触发此回调事件，例如播放短视频，拨打电话等。
                //通常需要暂停音乐播放
                //短暂性丢失焦点并作降音处理
                Log.d(TAG, "AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK");
//                if (mVideoView.isPlaying() && !mVideoView.isMute()) {
//                    mVideoView.setVolume(0.15f, 0.15f);
//                }
                synchronized (mFocusLock) {
//                    mResumeOnFocusGain = isPlaying();
//                    mPlaybackDelayed = false;
                    if (isPlaying()) {
                        pause();
                    }
                }
                break;
        }
    };

    private boolean canIn() {
        long ct = System.currentTimeMillis();
        if (ct - startTime < 2000) {
            Log.d(TAG, "2s内限制AudioFocus重复改变");
            return false;
        }
        startTime = ct;
        return true;
    }

    public static VideoManager getInstance(Context context) {
        if (mInstance == null) {
            synchronized (VideoManager.class) {
                if (mInstance == null) {
                    mInstance = new VideoManager(context);
                }
            }
        }
        return mInstance;
    }

    public VideoManager() {
        try {
            throw new Exception("VideoManager 不允许实例化");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private VideoManager(Context context) {
        init(context);
    }

    private void init(Context context) {
        this.mContext = context;
        mVideoView = new VideoView(context);
        mVideoView.setEnableAudioFocus(false);
        setListener();
        // 初始化音频属性和焦点请求
        mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);

        mPlaybackAttributes = new AudioAttributes.Builder()
                .setUsage(AudioAttributes.USAGE_MEDIA)
                .setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
                .build();
        mFocusRequest = new AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN)
                .setAudioAttributes(mPlaybackAttributes)
                .setAcceptsDelayedFocusGain(true)
                .setWillPauseWhenDucked(true)
                .setOnAudioFocusChangeListener(mAudioFocusChangeListener)
                .build();
    }

    /**
     * 说明：请求音频焦点
     */
    public void requestVideoFocus() {
        // 请求音频焦点
//        int res = mAudioManager.requestAudioFocus(mAudioFocusChangeListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
        int res = mAudioManager.requestAudioFocus(mFocusRequest);
        synchronized (mFocusLock) {
            if (res == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        play();
                    }
                }, 5000);
            }
        }
    }

    public void requestFocusResume() {
        int res = mAudioManager.requestAudioFocus(mFocusRequest);
        synchronized (mFocusLock) {
            if (res == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
                resume();
            }
        }
    }

    public void requestFocusPlayNext() {
        int res = mAudioManager.requestAudioFocus(mFocusRequest);
        synchronized (mFocusLock) {
            if (res == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
                playNext();
            }
        }
    }

    public void requestFocusPlayLast() {
        int res = mAudioManager.requestAudioFocus(mFocusRequest);
        synchronized (mFocusLock) {
            if (res == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
                playLast();
            }
        }
    }

    public void setVideoList(List<? extends VideoInfo> list) {
        if (!list.isEmpty()) {
            this.videoInfoList.clear();
            this.videoInfoList.addAll(list);
            this.index = 0;
        } else {
            try {
                throw new Exception("VideoInfoList为空！");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void addVideoList(VideoInfo info) {
        if (info != null) {
            this.videoInfoList.add(info);
        } else {
            try {
                throw new Exception("VideoInfoList为空！");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public boolean isPlaying() {
        return mVideoView.isPlaying();
    }

    public void play() {
        stop(false);
        if (!videoInfoList.isEmpty()) {
            isVideoPlaying = true;
            AiMediaCurrentInfoManager.getInstance(mContext).setCurrentIndex(index);
            Log.e(TAG, "开始播放：" + videoInfoList.get(index).getStreamUrl());
            mVideoView.setUrl(videoInfoList.get(index).getStreamUrl());
            mVideoView.start();
            //通知更新下拉栏
            notifySystemUpdateUI("play");
        } else {
            try {
                throw new Exception("VideoInfoList为空！请先添加媒体列表");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private String status = "play";

    /**
     * @date 2020/9/15
     * @desc 通知更新下拉栏
     */
    private void notifySystemUpdateUI(String status) {
        AiMediaBean currentMediaInfo = AiMediaCurrentInfoManager.getInstance(mContext).getCurrentMediaInfo();
        if (currentMediaInfo == null) {
            LogUtils.e("获取当前播放的媒体信息为null");
            return;
        }

        this.status = status;
        if (TextUtils.isEmpty(currentMediaInfo.getImageUrl()) || FileUtils.isFileExists(new File(getLocalPath(currentMediaInfo.getImageUrl())))) {
            sendNotify(currentMediaInfo.getImageUrl());
        } else {
            boolean orExistsDir = FileUtils.createOrExistsDir(DirectoryConstant.QUYI_IMG_CACHE);
            String url = currentMediaInfo.getImageUrl();
            if (orExistsDir) {
                long taskId = Aria.download(this)
                        .load(url)     //读取下载地址
                        .setFilePath(getLocalPath(currentMediaInfo.getImageUrl())) //设置文件保存的完整路径
                        .ignoreFilePathOccupy()
                        .create();//创建并启动下载
            }
        }
    }

    public void sendNotify(String filePath) {
        AiMediaBean currentMediaInfo = AiMediaCurrentInfoManager.getInstance(mContext).getCurrentMediaInfo();
        if (currentMediaInfo == null) {
            LogUtils.e("获取当前播放的媒体信息为null");
            return;
        }
        Intent intent = new Intent();
        intent.setAction(MEDIA_SYSTEM_UI);
        intent.putExtra("status", status);//play、stop、pause
        intent.putExtra("title", currentMediaInfo.getTitle());
        intent.putExtra("album", currentMediaInfo.getAlbum());
        intent.putExtra("imageUrl", getLocalPath(filePath));
        mContext.getApplicationContext().sendBroadcast(intent);
    }

    /**
     * @Desc 获取本地文件路径
     */
    private String getLocalPath(String url) {
        if (url == null) {
            return null;
        }
        String mVideoPath = "";
        int i = url.lastIndexOf('/');//一定是找最后一个'/'出现的位置
        if (i != -1) {
            url = url.substring(i);
            mVideoPath = DirectoryConstant.QUYI_IMG_CACHE +
                    url;
        }
        FileUtils.createOrExistsDir(DirectoryConstant.QUYI_IMG_CACHE);
        return mVideoPath;
    }

    public void playNext() {
        stop(false);
        if (!videoInfoList.isEmpty()) {
            index++;
            if (index >= 0 && index < videoInfoList.size()) {
                //请求音频焦点
//                requestVideoFocus();
                isVideoPlaying = true;
            } else {
                index = 0;
            }
            AiMediaCurrentInfoManager.getInstance(mContext).setCurrentIndex(index);
            Log.e(TAG, "开始播放：" + videoInfoList.get(index).getStreamUrl());
            mVideoView.setUrl(videoInfoList.get(index).getStreamUrl());
            mVideoView.start();
            //通知更新下拉栏
            notifySystemUpdateUI("play");
        } else {
            try {
                throw new Exception("VideoInfoList为空！请先添加媒体列表");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void playLast() {
        stop(false);
        if (!videoInfoList.isEmpty()) {
            index--;
            if (index >= 0 && index < videoInfoList.size()) {
                //请求音频焦点
//                requestVideoFocus();
                isVideoPlaying = true;
            } else {
                index = videoInfoList.size() - 1;
            }
            AiMediaCurrentInfoManager.getInstance(mContext).setCurrentIndex(index);
            Log.e(TAG, "开始播放：" + videoInfoList.get(index).getStreamUrl());
            mVideoView.setUrl(videoInfoList.get(index).getStreamUrl());
            mVideoView.start();
            //通知更新下拉栏
            notifySystemUpdateUI("play");
        } else {
            try {
                throw new Exception("VideoInfoList为空！请先添加媒体列表");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void pause() {
        mVideoView.pause();
        notifySystemUpdateUI("pause");
    }

    public void resume() {
        if (mVideoView != null) {
            //请求音频焦点
//            requestVideoFocus();
            mVideoView.resume();
        }
        notifySystemUpdateUI("play");
    }

    public void stop() {
        stop(true);
    }

    public void stop(boolean sendNotify) {
        isVideoPlaying = false;
        //释放焦点，该方法可根据需要来决定是否调用
        //若焦点释放掉之后，将不会再自动获得
//        mAudioManager.abandonAudioFocus(mAudioFocusChangeListener);

        mVideoView.pause();
        mVideoView.release();
        if (sendNotify) {
            notifySystemUpdateUI("stop");
        }
    }

    public void replay() {
        if (isPlaying()) {
            isVideoPlaying = false;
            mVideoView.pause();
            mVideoView.release();
        }
        play();
    }

    public void setListener() {
        mVideoView.setOnStateChangeListener(new VideoView.OnStateChangeListener() {
            @Override
            public void onPlayerStateChanged(int playerState) {

            }

            @Override
            public void onPlayStateChanged(int playState) {
                switch (playState) {
                    //调用release方法会回到此状态
                    case VideoView.STATE_ERROR:
                        Log.e(TAG, "STATE_ERROR：播放错误");
                        sendReceiverSpeakText("音频播放错误，请重试");
                        break;
                    case VideoView.STATE_PREPARING:
                        Log.e(TAG, "STATE_PREPARING：播放准备中…");
                        break;
                    case VideoView.STATE_PREPARED:
                        Log.e(TAG, "STATE_PREPARED：播放准备好了");
                        mAudioManager.requestAudioFocus(mFocusRequest);
                        break;
                    case VideoView.STATE_PLAYING:
                        Log.e(TAG, "STATE_PLAYING：播放中…");
                        break;
                    case VideoView.STATE_PAUSED:
                        Log.e(TAG, "STATE_PAUSED：播放暂停");
                        break;
                    case VideoView.STATE_PLAYBACK_COMPLETED:
                        Log.e(TAG, "STATE_PLAYBACK_COMPLETED：播放完成");
                        break;
                    case VideoView.STATE_BUFFERING:
                        Log.e(TAG, "STATE_BUFFERING：播放正在缓冲…");
                        break;
                    case VideoView.STATE_BUFFERED:
                        Log.e(TAG, "STATE_BUFFERED：播放缓冲完毕");
                        mAudioManager.requestAudioFocus(mFocusRequest);
                        break;
                }
            }
        });
    }

    private void sendReceiverSpeakText(String content) {
        Intent intent = new Intent();
        intent.setAction(Constant.action_aiyisheng_text_speech);
        intent.putExtra("content", content);
        mContext.sendBroadcast(intent);
    }
}
